﻿using IOP.Orleans.Client;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace IOP.Orleans.Client
{
    /// <summary>
    /// 奥尔良客户端监控服务
    /// </summary>
    public class OrleansClientMonitorHostService : IHostedService
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<OrleansClientMonitorHostService> _Logger;
        /// <summary>
        /// 奥尔良客户端
        /// </summary>
        private readonly IClusterClient _OrleansClient;
        /// <summary>
        /// 配置
        /// </summary>
        private readonly ClientHostOptions _Options;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        public OrleansClientMonitorHostService(ILogger<OrleansClientMonitorHostService> logger, 
            IClusterClient client, IOptions<ClientHostOptions> options)
        {
            _Logger = logger;
            _OrleansClient = client;
            _Options = options.Value;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await _OrleansClient.Connect(async (e) =>
            {
                _Logger.LogError($"The OrleansClient was connected failed, error msg: {e.Message} \r\n {e.StackTrace}, begin retry");
                await Task.Delay(_Options.ClientRetryInterval);
                return true;
            });
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await _OrleansClient.Close();
        }
    }
}
